package com.ext.aic;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Environment;

import com.ext.aic.constants.EBusConstants;
import com.ext.aic.utils.RefreshUtils;
import com.ext.aic.utils.ToastyUtils;
import com.ext.aic.utils.http.HttpUtils;
import com.eyinfo.android_pure_utils.ebus.EBus;
import com.eyinfo.android_pure_utils.logs.CrashHandler;
import com.eyinfo.android_pure_utils.logs.CrashUtils;
import com.eyinfo.android_pure_utils.utils.JsonUtils;
import com.eyinfo.mpkv.MPLocalKV;
import com.eyinfo.storage.files.FileUtils;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions;

import java.io.File;
import java.lang.ref.WeakReference;

import io.github.eyinfo.okrx.OkRx;
import io.github.eyinfo.okrx.events.OnBeanParsingJsonListener;
import lombok.Getter;

/**
 * 创收app 主启动程序
 */
public class AICApplication extends Application {

    private static WeakReference<Activity> currentActivityRef;

    @Getter
    private static volatile AICApplication instance;

    @Getter
    private TextRecognizer textRecognizer;

    private int runningActivities = 0;
    private boolean starting = false;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        crashHandler.init(this);
        MPLocalKV.getInstance().init(getApplicationContext());
        RefreshUtils.init();
        ToastyUtils.getInstance().config(getApplicationContext());
        HttpUtils.getInstance().init(this);
        initNet();
        AICManager.getInstance().init(getApplicationContext());
        starting = true;
        registerActivity();

        initOCR();
    }

    private void initNet() {
        OkRx.getInstance().initialize(this)
                .setOnBeanParsingJsonListener(new OnBeanParsingJsonListener() {
                    @Override
                    public Object onBeanParsingJson(String response, Class dataClass, boolean isCollectionDataType) {
                        if (isCollectionDataType) {
                            return JsonUtils.parseArray(response, dataClass);
                        } else {
                            return JsonUtils.parseT(response, dataClass);
                        }
                    }
                })
                .build();
    }

    private void initOCR() {
        ChineseTextRecognizerOptions options = new ChineseTextRecognizerOptions.Builder().build();
        textRecognizer = TextRecognition.getClient(options);
    }

    private CrashHandler crashHandler = new CrashHandler() {
        @Override
        protected void onLogIntercept(Throwable throwable) {
            String crashInfo = CrashUtils.getCrashInfo(throwable);
            String fileName = String.format("%s_%s.txt", System.currentTimeMillis(), "crash");
            File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File file = FileUtils.getFile(directory, fileName);
            FileUtils.save(crashInfo, file);
        }
    };

    private void registerActivity() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityResumed(Activity activity) {
                currentActivityRef = new WeakReference<>(activity);
            }

            // 其他生命周期方法留空
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                runningActivities++;
                if (runningActivities > 0 && !starting) {
                    EBus.getInstance().post(EBusConstants.windowContentChangedEvent);
                }
                starting = false;
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                if (runningActivities > 0 && --runningActivities == 0 || runningActivities == 0) {
                    EBus.getInstance().post(EBusConstants.windowContentChangedEvent);
                }
                starting = false;
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    public static Activity getCurrentActivity() {
        return currentActivityRef != null ? currentActivityRef.get() : null;
    }

    public static boolean isActivityTop(Class<?> activityClass) {
        Activity currentActivity = currentActivityRef != null ? currentActivityRef.get() : null;
        return currentActivity != null && currentActivity.getClass().equals(activityClass);
    }
}
